<?php
// 签名公司效验地址 https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
// 方法1 get_access_token() 获取 access_token
// 方法2 get_jsapi_ticket() 获取 jsapi_ticket
// 方法3 fen_xaing_config($url) 获取js分享配置文件,需要传入分享的地址(#号以前的)
class WeiXingInit
{

    public $APPID = '微信公众号appid';
    public $SECRET = '微信公众号secret';

    // access_token 存储文件 频繁刷新access_token会导致api调用受限，影响自身业务，开发者必须在自己的服务全局缓存access_token
    public $fileName_access = 'access_token';
    // jsapi_ticket 存储文件 频繁刷新jsapi_ticket会导致api调用受限，影响自身业务，开发者必须在自己的服务全局缓存jsapi_ticket
    public $fileName_jsapi_ticket = 'jsapi_ticket';

    public $debug = false;

    // 获取 access_token
    public function get_access_token()
    {
        $data = [];

        if (is_file($this->fileName_access)) {

            // 验证是否过期
            $time = time();
            $data = json_decode(file_get_contents($this->fileName_access), true);

            if (($time - $data['time']) > ($data['expires_in'] - 100)) {
                $data = $this->access_token_get_save();
            }
        } else {
            $data = $this->access_token_get_save();
        }

        return $data;
    }

    // access_token 获取保存
    public function access_token_get_save()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token";
        $post_string = "grant_type=client_credential&appid=" . $this->APPID . "&secret=" . $this->SECRET;

        $url = $url . '?' . $post_string;

        $data = json_decode($this->curl($url), true);
        $data['time'] = time();
        file_put_contents($this->fileName_access, json_encode($data));
        return $data;
    }

    // 获取 jsapi_ticket
    public function get_jsapi_ticket()
    {
        $data = [];

        if (is_file($this->fileName_jsapi_ticket)) {

            // 验证是否过期
            $time = time();
            $data = json_decode(file_get_contents($this->fileName_jsapi_ticket), true);

            if (($time - $data['time']) > ($data['expires_in'] - 100)) {
                $data = $this->jsapi_ticket_get_save();
            }
        } else {
            $data = $this->jsapi_ticket_get_save();
        }

        return $data;
    }

    // jsapi_ticket 获取保存
    public function jsapi_ticket_get_save()
    {
        $data = [];

        $data_access = $this->get_access_token();

        if (!empty($data_access['access_token'])) {
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
            $post_string = "access_token=" . $data_access['access_token'] . "&type=jsapi";

            $url = $url . '?' . $post_string;

            $data = json_decode($this->curl($url, $post_string), true);
            $data['time'] = time();
            file_put_contents($this->fileName_jsapi_ticket, json_encode($data));
        }
        return $data;
    }

    // 生成随机字符串
    public function generate_password($length = 8)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $password = "";
        for ($i = 0; $i < $length; $i++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $password .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $password;
    }

    // 微信分享config
    public function fen_xaing_config($url)
    {
        $noncestr = $this->generate_password(15);
        $time = time();
        return [
            'debug' => $this->debug,
            'appId' => $this->CORPID, // 必填，公众号的唯一标识
            'timestamp' => $time, // 必填，生成签名的时间戳
            'nonceStr' => $noncestr, // 必填，生成签名的随机串
            'signature' => $this->get_qian_ming($url, $time, $noncestr), // 必填，签名
            'jsApiList' => ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone'], // 必填，需要使用的JS接口列表
        ];
    }

    // 生成签名
    public function get_qian_ming($url, $t_time, $noncestr)
    {
        $data_jsapi = $this->get_jsapi_ticket();

        $str = "";
        if (!empty($data_jsapi['ticket'])) {
            $jsapi_ticket = $data_jsapi['ticket'];
            $timestamp = $t_time;

            $str = 'jsapi_ticket=' . $jsapi_ticket . '&noncestr=' . $noncestr . '&timestamp=' . $timestamp . '&url=' . $url;

            $str = sha1($str);
        }
        return $str;

    }

    public function curl($url, $post_string = '')
    {

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;

    }

}

$weiXingInit = new WeiXingInit();
$url = $_GET['url'];

$info = $weiXingInit->fen_xaing_config($url);

header('Access-Control-Allow-Origin:*'); //支持全域名访问，不安全，部署后需要固定限制为客户端网址
header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); //支持的http 动作
header('Access-Control-Allow-Headers:x-requested-with,content-type'); //响应头 请按照自己需求添加。
$result = array('code' => 1, 'msg' => '查询成功', 'data' => $info, 'url' => '', 'wait' => '');

echo json_encode($result);exit;
